from django import forms
from web import models
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from django.conf import settings
import random
from utils.tencent.sms import send_sms_single
from django_redis import get_redis_connection
from utils import encrypt


class BootStrapForm(object):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入%s' % (field.label)


class DevinfoModelForm(BootStrapForm, forms.ModelForm):
    class Meta:
        model = models.DevInfo
        fields = ['mobile_phone', 'devname', 'send_flag', 'devtopic', 'devsym', 'devtype', 'detail']
        labels = {
            'mobile_phone': '账号',
            'devname': '设备名',
            'send_flag': '订阅/发布',
            'devtopic': 'Topic',
            'devsym': '数据符号',
            'devtype': '设备类型',
            'detail': '详情',
        }
        widgets = {
            'mobile_phone': forms.TextInput(),
            'devname': forms.TextInput(),
            'send_flag': forms.widgets.Select(),
            'devtopic': forms.TextInput(),
            'devsym': forms.TextInput(),
            'devtype': forms.widgets.Select(),
            'detail': forms.Textarea,
        }

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_devname(self):
        devname = self.cleaned_data['devname']
        exists = models.DevInfo.objects.filter(mobile_phone=self.request.tracer.mobile_phone).filter(devname=devname).exists()
        if exists:
            raise ValidationError('设备名已存在')
        return devname

    def clean_devtopic(self):
        devtopic = self.cleaned_data['devtopic']
        send_flag = self.cleaned_data.get('send_flag')
        matchstr = "~!@#$￥%^&*()=+-*\<>,.，[]'\'\""
        #exists = models.DevInfo.objects.filter(mobile_phone=self.request.tracer.mobile_phone).filter(devtopic=devtopic).exists()
        if send_flag == '1':
            exist1 = models.DevInfo.objects.filter(devtopic=devtopic).filter(send_flag='1').exists()
            if exist1:
                raise ValidationError('Topic已被订阅，请重新设置')
        elif send_flag == '2':
            exist2 = models.DevInfo.objects.filter(mobile_phone=self.request.tracer.mobile_phone).filter(devtopic=devtopic).filter(send_flag='2').exists()
            if exist2:
                raise ValidationError('您已发布过该Topic，请勿重复制定')
        for i in devtopic:
            if i in matchstr:
                str = 'Topic命名格式有问题，{}不合法,建议用/'.format(i)
                raise ValidationError(str)
        return devtopic

    def clean_devtype(self):
        devtype = self.cleaned_data['devtype']
        send_flag = self.cleaned_data.get('send_flag')
        print(devtype,send_flag)
        if send_flag == '2' and devtype == '2':
            raise ValidationError('抱歉，暂时不支持这种制定')
        return devtype




class DevinfodetailModelForm(BootStrapForm, forms.Form):
    SUBSCRIBED = '订阅中'
    UNSUBSCRIBED = '未订阅'
    SUB_CHOICES = (
        (SUBSCRIBED, '订阅中'),
        (UNSUBSCRIBED, '未订阅')
    )
    send_choices = (
        ('1', '订阅'),
        ('2', '发布'),
    )
    devtype_choices = (
        ('1', '数据'),
        ('2', '视频'),
    )
    mobile_phone1 = forms.CharField(label='账号', widget=forms.TextInput())
    devname1 = forms.CharField(label='设备名', widget=forms.TextInput())

    send_flag1 = forms.CharField(label='订阅/发布', widget=forms.widgets.Select(choices=send_choices))
    devtopic1 = forms.CharField(label='Topic', widget=forms.TextInput())
    devsym1 = forms.CharField(label='数据符号', widget=forms.TextInput())

    devtype1 = forms.CharField(label='设备类型', widget=forms.widgets.Select(choices=devtype_choices))
    detail1 = forms.CharField(label='详情', widget=forms.Textarea)
    devrecord1 = forms.CharField(label='创建时间', widget=forms.TextInput())


class ModelInfoModelForm(BootStrapForm, forms.ModelForm):
    class Meta:
        model = models.ModelInfo
        fields =['mobile_phone', 'modelname', 'detail']
        labels = {
            'mobile_phone': '账号',
            'modelname': '模块名',
            'detail': '详情',
        }
        widgets = {
            'mobile_phone': forms.TextInput(),
            'modelname': forms.TextInput(),
            'detail': forms.Textarea,
        }



